/**
 * A simple uuid generator, support prefix and template pattern.
 * @example
 *  uuid('v-') // -> v-xxx
 *  uuid('v-ani-%{s}-translate')  // -> v-ani-xxx
 */
export function uuid(prefix) {
  const id = Math.floor(Math.random() * 10000).toString(36);
  return prefix
    ? ~prefix.indexOf("%{s}")
      ? prefix.replace(/%\{s\}/g, id)
      : prefix + id
    : id;
}

export const getUUID = function () {
  var s = [];
  var hexDigits = "0123456789abcdef";
  for (var i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }
  s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23] = "-";
  var uuid = s.join("");
  return uuid;
};

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null;
  }
  const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
  let date;
  if (typeof time === "object") {
    date = time;
  } else {
    if (typeof time === "string") {
      if (/^[0-9]+$/.test(time)) {
        // support "1548221490638"
        time = parseInt(time);
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), "/");
      }
    }

    if (typeof time === "number" && time.toString().length === 10) {
      time = time * 1000;
    }
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  };
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key];
    // Note: getDay() returns 0 on Sunday
    if (key === "a") {
      return ["日", "一", "二", "三", "四", "五", "六"][value];
    }
    return value.toString().padStart(2, "0");
  });
  return time_str;
}

const commonMethod = {
  // 格式化时间
  formatDate(date) {
    if (!date) return "";
    const dateTime = new Date(date);
    const YY = dateTime.getFullYear();
    const MM =
      dateTime.getMonth() + 1 < 10
        ? '0' + (dateTime.getMonth() + 1)
        : dateTime.getMonth() + 1;
    const D =
      dateTime.getDate() < 10 ? '0' + dateTime.getDate() : dateTime.getDate();
    const hh =
      dateTime.getHours() < 10
        ? '0' + dateTime.getHours()
        : dateTime.getHours();
    const mm =
      dateTime.getMinutes() < 10
        ? '0' + dateTime.getMinutes()
        : dateTime.getMinutes();
    const ss =
      dateTime.getSeconds() < 10
        ? '0' + dateTime.getSeconds()
        : dateTime.getSeconds();
    return `${YY}-${MM}-${D} ${hh}:${mm}:${ss}`;
  },
  formatDate2(date) {
    const dateTime = new Date(date);
    const YY = dateTime.getFullYear();
    const MM =
      dateTime.getMonth() + 1 < 10
        ? '0' + (dateTime.getMonth() + 1)
        : dateTime.getMonth() + 1;
    const D =
      dateTime.getDate() < 10 ? '0' + dateTime.getDate() : dateTime.getDate();
    return `${YY}-${MM}-${D} `;
  },
  //yyyy-mm-dd 转换为时间戳
  timestampGet(timeString) {
    const thisTime = timeString.replace(/ /g, '/')
    let nowTime = new Date(thisTime)
    nowTime = nowTime.getTime()
    return nowTime
  }
}

/**
 * 树形数组中，根据查找某个元素的所有父节点
 * @param {*} treeList 
 * @param {*} code 
 * @param {*} path 
 * @returns 返回所有父节点的数组
 */
const findParent = function (treeList, code, path = []) {
  if (!treeList) return [];
  for (const data of treeList) {
    path.push(data);
    if (data.url == code) return path;
    if (data.childrenList && data.childrenList.length) {
      const findchildren = this.findParent(data.childrenList, code, path);
      if (findchildren.length) return findchildren;
    }
    path.pop();
  }
  return [];
}

export const findChildUrl = function (obj) {
  let url = '';
  if (obj.children && obj.children.length) {
    let first = obj.children[0];
    url = findChildUrl(first);
  } else {
    url = obj.url;
  }
  return url;
}

// 把两个对象数组合并
export const mergeUniquely = function (arr1 = [], arr2 = []) {
  const newArr = arr1.concat(arr2);
  newArr.sort((a, b) => b.value - a.value)
  const map = {};
  const res = [];
  newArr.forEach(el => {
    if (!map[el['name']]) {
      res.push(el);
      map[el['name']] = 1;
    }
  })
  return res
}

export function pad(num, n = 2) {
  let len = num.toString().length
  while (len < n) {
    num = '0' + num
    len++
  }
  return num
}

export function formatTime(interval) {
  interval = interval | 0
  const minute = pad((interval / 60) | 0)
  const second = pad(interval % 60)
  return `${minute}:${second}`
}




